#! /bin/sh

OK=0
WARNING=1
CRITICAL=2
UNKNOWN=3

if [ ! -f "$ARC_CONFIG" ]; then
    if [ -f "/etc/arc.conf" ]; then
        arcconf="/etc/arc.conf"
    elif [ -f "/etc/grid-security/arc.conf" ]; then
	arcconf="/etc/grid-security/arc.conf"
    else
	echo "UNKNOWN: arc.conf not found"
	exit $UNKNOWN
    fi
    export ARC_CONFIG=$arcconf
fi

usage()
{
cat << EOF
usage: $0 options

This script checks the number of files in 'controldir' defined in arc.conf.

OPTIONS:
   -h      Show this message
   -c      Set critical threshold (number of files)	[100000 default]
   -w      Set warn threshold (number of files)		[ 50000 default]
EOF
}

CRIT_THRESH=
WARN_THRESH=
while getopts “hw:c:” OPTION
do
     case $OPTION in
         h)
             usage
             exit $UNKNOWN
             ;;
         w)
             let -i WARN_THRESH=$OPTARG
             ;;
         c)
             let -i CRIT_THRESH=$OPTARG
             ;;
         ?)
             usage
             exit $UNKNOWN
             ;;
     esac
done
if [[ -z $CRIT_THRESH ]]
then
    let -i CRIT_THRESH=100000
fi
if [[ -z $WARN_THRESH ]]
then
    let -i WARN_THRESH=50000
fi

################################################################
controldir=$(grep controldir $ARC_CONFIG | sed -e s/controldir=//g -e s/\"//g)
if ! [[ -d "$controldir" ]]; then
    echo "WARNING: controldir ambiguous in arc.conf"
    exit $WARNING
fi


let -i num_files=$(find $controldir -maxdepth 1 | wc -l)

msg="$num_files files in $controldir |/=$num_files;$WARN_THRESH;$CRIT_THRESH;0;$CRIT_THRESH"


if [[ $num_files -gt $CRIT_THRESH ]]
then
    echo -en "CRITICAL: "
    echo -e "$msg"
    exit $CRITICAL
elif [[ $num_files -gt $WARN_THRESH ]]
then
    echo -en "WARNING: "
    echo -e $msg
    exit $WARNING
elif [[ $num_files -lt $CRIT_THRESH ]] && [[ $num_files -lt $WARN_THRESH ]]
then
    echo -en "OK: "
    echo -e $msg
    exit $OK
else
    echo -en "UNKNOWN: "
    echo -e $msg
    exit $UNKNOWN
fi
